﻿<?php 
require_once("maincore.php");
if (!defined("THNOJ")) die("Outside of the site");
session_start();
if (!isset($_SESSION['user_id'])){
	require_once("oj-header.php");
	echo "<a href='loginpage.php'>Please Login First!</a>";
	require_once("oj-footer.php");
	exit(0);
}
require_once("include/db_info.inc.php");
require_once("include/const.inc.php");
$user_id=$_SESSION['user_id'];


if (isset($_POST['id'])) {
	$id=intval($_POST['id']);
	
}else if (isset($_POST['pid']) && isset($_POST['cid'])){
	$pid=intval($_POST['pid']);
	$cid=intval($_POST['cid']);
	// check user if private
	$sql="SELECT `private` FROM `contest` WHERE `contest_id`='$cid' AND `start_time`<=NOW() AND `end_time`>NOW()";
	$result=mysql_query($sql);
	$rows_cnt=mysql_num_rows($result);
	if ($rows_cnt<1){
		echo "Bạn không thể nộp bài, có thể vì bạn không được tham gia hoặc kì thi đã hết hạn!!";
		mysql_free_result($result);
		require_once("oj-footer.php");
		exit(0);
	}else{
		$row=mysql_fetch_array($result);
		$isprivate=intval($row[0]);
		mysql_free_result($result);
		if ($isprivate==1){
			$sql="SELECT count(*) FROM `privilege` WHERE `user_id`='$user_id' AND `rightstr`='c$cid'";
			$result=mysql_query($sql) or die (mysql_error()); 
			$row=mysql_fetch_array($result);
			$ccnt=intval($row[0]);
			mysql_free_result($result);
			if ($ccnt<=0){
				require_once("contest-header.php");
				echo "Bạn không được tham gia!\n";
				require_once("oj-footer.php");
				exit(0);
			}
		}
	}
	$sql="SELECT `problem_id` FROM `contest_problem` WHERE `contest_id`='$cid' AND `problem_id`='$pid'";
	if ($DEBUG) echo "<br>sql3:$sql";
	$result=mysql_query($sql);
	$rows_cnt=mysql_num_rows($result);
	if ($rows_cnt!=1){
		require_once("contest-header.php");
		echo "<h2>Không có bài toán!</h2>";
		require_once("oj-footer.php");
		mysql_free_result($result);
		exit(0);
	}else{
		$row=mysql_fetch_object($result);
		$id=intval($row->problem_id);
		$sql="SELECT title FROM `problem` WHERE `problem_id`='$id' limit 1";
		if ($DEBUG) echo "<br>sql3:$sql";
		$result=mysql_query($sql);
		$row=mysql_fetch_object($result);
		$title=$row->title;
		mysql_free_result($result);
	}
}else{
	echo "<h2>Không có bài toán!</h2>";
	exit(0);
}

$language=intval($_POST['language']);
if ($DEBUG) {
	echo "<br>NNLT:$language";
	//exit(0);
}
if ($language>9 || $language<0) $language=0;
$language=strval($language);


$source=$_POST['source'];
$shared=($_POST['sharecode']?1:0);
if(get_magic_quotes_gpc())
	$source=stripslashes($source);
$source=mysql_real_escape_string($source);
//$source=trim($source);
//use append Main code
$append_file="$OJ_DATA/$id/append.$language_ext[$language]";
if(isset($OJ_APPENDCODE)&&$OJ_APPENDCODE&&file_exists($append_file)){
	
     $source.=mysql_real_escape_string("\n".file_get_contents($append_file));
}
//end of append 


$len=strlen($source);
//echo $source;




setcookie('lastlang',$language,time()+360000);

$ip=$_SERVER['REMOTE_ADDR'];

if ($len<2){
	require_once("oj-header.php");
	echo "Source Code quá ngắn!";
	require_once("oj-footer.php");
	exit(0);
}
if ($len>65536){
	require_once("oj-header.php");
	echo "Source Code quá dài!";
	require_once("oj-footer.php");
	exit(0);
}

// last submit

$sql="SELECT `in_date` from `solution` where `user_id`='$user_id' and in_date>now()-30 order by `in_date` desc limit 1";
$res=mysql_query($sql);
if (mysql_num_rows($res)==1){
	//$row=mysql_fetch_row($res);
	//$last=strtotime($row[0]);
	//$cur=time();
	//if ($cur-$last<10){
		require_once('oj-header.php');
		echo "Bạn không được nộp bài quá nhanh. Vui lòng chờ 30 giây ...<br>";
		require_once('oj-footer.php');
		exit(0);
	//}
}


if (!isset($pid)){
$sql="INSERT INTO solution(problem_id,user_id,in_date,language,ip,code_length,sharing)
	VALUES('$id','$user_id',NOW(),'$language','$ip','$len',$shared)";
}else{
$sql="INSERT INTO solution(problem_id,user_id,in_date,language,ip,code_length,contest_id,num,sharing)
	VALUES('$id','$user_id',NOW(),'$language','$ip','$len','$cid','$pid',$shared)";
}
mysql_query($sql);
$insert_id=mysql_insert_id();

$sql="INSERT INTO `source_code`(`solution_id`,`source`)VALUES('$insert_id','$source')";
mysql_query($sql);
//echo $sql;
$guimail=true;
$sql="SELECT `in_date` from `solution` where in_date>now()-600 and sent=1 order by `in_date` desc limit 1";
$res=mysql_query($sql);
if ($numb=mysql_num_rows($res)){
	$guimail=false;//qua nhanh
} 
else {
	$sql="select * from solution where sent=0 order by `in_date` desc";
	$result=mysql_query($sql) or die($sql);
	if (mysql_num_rows($result)) {
		$dshs=",";
		$dsbai=",";
		$dsgiai="";
		$dsid="";
		while ($data=mysql_fetch_array($result)) {
			if (strpos($dshs,",".$data['user_id'].",")===false) $dshs.=$data['user_id'].",";
			if (strpos($dsbai,",".$data['problem_id'].",")===false) $dsbai.=$data['problem_id'].",";
			$dsgiai.="<a href='http://chamthi.net/bai.php?id=".$data['solution_id']."'>Bài nộp ".$data['solution_id'].": ".$data['user_id']."/".$data['problem_id']."</a> thành công ".$data['result']." (".$data['pass_rate'].")<br/>";
			$dsid.=$data['solution_id'].",";
		}
		$subject = '[chamthi.net] Bài nộp mới '.substr($dshs,1,-1)."/".substr($dsbai,1,-1);
		$message = "Hi,<br/>".$dsgiai.'<br/>
Chúc vui,<br/>
chamthi.net
';
		$headers = "MIME-Version: 1.0" . "\r\n";
		$headers .= "Content-type:text/html;charset=utf-8" . "\r\n";
		$headers .= 'From: '.(isset($myemail)?$myemail:$admin_email). "\r\n";
		if ($DEBUG) {
			echo "dsid= ".$dsid."<br/>";
		}
		//if (isset($_SESSION['user_ref_email']))
			//$headers .= 'Bcc: ' .$_SESSION['user_ref_email']. "\r\n";
							//'Reply-To: '.(isset($myemail)?$myemail:"chamthitructuyen@gmail.com"). "\r\n" .
							//'X-Mailer: PHP/' . phpversion();


		//if (isset($_SESSION['user_ref_email']))
			//mail($_SESSION['user_ref_email'], $subject, str_replace("%user%",$myid.$myname,$message), $headers);
		//if (isset($myemail) && $guimail)
		//	mail($myemail, $subject, $message, $headers);
		//if (isset($_SESSION['user_ref_email']))
			//mail($_SESSION['user_ref_email'], $subject, $message, $headers);
		/* alert to super admin */
		if ($guimail)
			mail("chamthitructuyen@gmail.com", $subject, $message, $headers);
		if ($DEBUG) {
			echo "Send mail to "."chamthitructuyen@gmail.com"."/".$subject. "/" . $message."/".$headers;
		}	
		/* update sent field to 1 */
		$sql = "update solution set sent=1 where solution_id in (".substr($dsid,0,-1).")";
		mysql_query($sql) or die("Can not update sent field via ".$sql);
		//write_log($sql);
	}
}
	 $statusURI=strstr($_SERVER['REQUEST_URI'],"submit",1)."status.php";
	 if (isset($cid)) 
	    $statusURI.="?cid=$cid";
	    
        $sid="";
        if (isset($_SESSION['user_id'])){
                $sid.=session_id().$_SERVER['REMOTE_ADDR'];
        }
        if (isset($_SERVER["REQUEST_URI"])){
                $sid.=$statusURI;
        }
   // echo $statusURI."<br>";
  
        $sid=md5($sid);
        $file = "cache/cache_$sid.html";
    //echo $file;  
    if($OJ_MEMCACHE){
		$mem = new Memcache;
                if($OJ_SAE)
                        $mem=memcache_init();
                else{
                        $mem->connect($OJ_MEMSERVER,  $OJ_MEMPORT);
                }
        $mem->delete($file,0);
    }
	else if(file_exists($file)) 
	     unlink($file);
    //echo $file;
    

	header("Location: $statusURI");

	
?>
